﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using ST.Common.Data;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using ST.Buz.Base;
using ST.Buz.Base.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using ST.Buz.Base.Enums;
using ST.Common.Util.Security;
using Microsoft.Data.SqlClient;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using ST.Buz.Base.ViewModel;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;

namespace ST.Buz.Service
{
	public partial interface IServiceSysTableLog
	{
		/// <summary>
		/// 新增日志
		/// </summary>
		/// <param name="sessionCurrent"></param>
		/// <param name="dt"></param>
		/// <param name="content"></param>
		/// <returns></returns>
		int Add(UserSession sessionCurrent, TableCode tblCode, int infoID, string ip, string content, DateTime? dt = null, bool withinTrans = false);

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sessionCurrent"></param>
		/// <param name="title"></param>
		/// <param name="obj"></param>
		/// <param name="dt"></param>
		/// <returns></returns>
		int Add(UserSession sessionCurrent, TableCode tblCode, int infoID, string ip, string title, object obj, DateTime? dt = null, bool withinTrans = false);

		/// <summary>
		/// 获取分页列表
		/// </summary>
		PageData GetPageList(VMS_Sys_TableLog searchModel);

		int GetCount(VMS_Sys_TableLog searchModel);
	}

	public partial class ServiceSysTableLog
	{
		public ServiceSysTableLog(BuzContext ctx,
			ILogger<ServiceSysTableLog> log)
		{
			context = ctx;
			logger = log;
		}

		private IQueryable<Sys_TableLog> GetQuery(VMS_Sys_TableLog searchModel)
		{
			var query = from m in context.SysTableLog where m.TableID == searchModel.tblid && m.InfoID == searchModel.infoid select m;
			if (!string.IsNullOrEmpty(searchModel.content))
			{
				query = query.Where(m => EF.Functions.Like(m.LogContent, "%" + searchModel.content + "%"));
			}
			if (!string.IsNullOrEmpty(searchModel.logman))
			{
				query = query.Where(m => m.LogManName == searchModel.logman);
			}
			if (!string.IsNullOrEmpty(searchModel.logmanip))
			{
				query = query.Where(m => m.LogManIP == searchModel.logmanip);
			}
			if (searchModel.logmanid.HasValue)
			{
				query = query.Where(m => m.LogManID == searchModel.logmanid.Value);
			}
			if (searchModel.date_s != DateTime.MinValue)
			{
				query = query.Where(m => m.LogTime >= searchModel.date_s);
			}
			if (searchModel.date_e != DateTime.MinValue)
			{
				query = query.Where(m => m.LogTime <= searchModel.date_e);
			}
			return query;
		}

		/// <summary>
		/// 分页列表
		/// </summary>
		public PageData GetPageList(VMS_Sys_TableLog searchModel)
		{
			PageData result = null;
			try
			{
				searchModel.Validate();
				var query = GetQuery(searchModel);
				switch (searchModel.sortby)
				{
					default:
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.ID) : query.OrderByDescending(e => e.ID);
						break;
				}
				result = new PageData(searchModel.pnum.Value, searchModel.psize.Value);
				result.Load(query);
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取分页数据出错");
				throw new BuzException("获取分页数据失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return result;
		}

		public int GetCount(VMS_Sys_TableLog searchModel)
		{
			var query = GetQuery(searchModel);
			return query.Count();
		}

		private int Add(Sys_TableLog model, UserSession sessionCurrent)
		{
			try
			{
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}

				using (var trans = context.Database.BeginTransaction())
				{
					try
					{
						#region 事务具体操作
						Add(model);
						#endregion

						trans.Commit();

						return model.ID;
					}
					catch (Exception ex)
					{
						trans.Rollback();
						throw ex.InnerException ?? ex;
					}
				}
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "保存对象信息出错");
				throw new BuzException("数据库保存失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 新增
		/// </summary>
		public int Add(UserSession sessionCurrent, TableCode tblCode, int infoID, string ip, string content, DateTime? dt = null, bool withinTrans = false)
		{
			try
			{
				if (infoID <= 0)
				{
					throw new BuzException("相关记录ID不能为空");
				}
				if (string.IsNullOrEmpty(ip))
				{
					ip = GetRequestIP();
				}
				Sys_TableLog log = new Sys_TableLog();
				log.InfoID = infoID;
				log.LogContent = content;
				log.LogManID = sessionCurrent.UserID;
				log.LogManIP = ip;
				log.LogManName = sessionCurrent.UserName;
				//log.LogNo =;
				log.LogTime = dt == null ? DateTime.Now : dt.Value;
				//log.LogType =;
				log.OrgID = sessionCurrent.OrgID;
				log.TableID = (int)tblCode;
				if (withinTrans)
				{
					return Add(log);
				}
				else
				{
					return Add(log, sessionCurrent);
				}
			}
			catch
			{
				return 0;
			}
		}

		/// <summary>
		/// 新增
		/// </summary>
		/// <param name="sessionCurrent"></param>
		/// <param name="tblCode"></param>
		/// <param name="infoID"></param>
		/// <param name="ip"></param>
		/// <param name="title"></param>
		/// <param name="obj"></param>
		/// <param name="dt"></param>
		/// <param name="withinTrans">该操作是否已经在事务中</param>
		/// <returns></returns>
		public int Add(UserSession sessionCurrent, TableCode tblCode, int infoID, string ip, string title, object obj, DateTime? dt = null, bool withinTrans = false)
		{
			try
			{
				if (infoID <= 0)
				{
					throw new BuzException("相关记录ID不能为空");
				}
				if (string.IsNullOrEmpty(ip))
				{
					ip = GetRequestIP();
				}
				Sys_TableLog log = new Sys_TableLog();
				log.InfoID = infoID;
				if (obj == null)
				{
					log.LogContent = title;
				}else{
					log.LogContent = title + Newtonsoft.Json.JsonConvert.SerializeObject(obj, new JsonSerializerSettings()
					{
						NullValueHandling = NullValueHandling.Ignore
					});
				}
				log.LogManID = sessionCurrent.UserID;
				log.LogManIP = ip;
				log.LogManName = sessionCurrent.UserName;
				//log.LogNo =;
				log.LogTime = dt == null ? DateTime.Now : dt.Value;
				//log.LogType =;
				log.OrgID = sessionCurrent.OrgID;
				log.TableID = (int)tblCode;
				if (withinTrans)
				{
					return Add(log);
				}
				else
				{
					return Add(log, sessionCurrent);
				}
			}
			catch
			{
				return 0;
			}
		}
	}
}